// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
        speed:200,
        target:cc.Node,
        _time:0,
        _range:cc.p(0,0),
        _acc:cc.p(0,0)
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad: function  () {
        var screenSize=cc.view.getVisiableSize();

        this._range.x=screenSize.width/2-this.target.width/2;

        this._range.y=screenSize.height/2-this.target.height/2;

    
        cc.systemEvent.setAccelerometerEnabled(true);

        cc.systemEvent.on(cc.systemEvent.EventType.DEVICEMOTION ,this.onDeviceMotionEvent);

    },
    onDeviceMotionEvent: function (event) {

        this._acc.x=event.acc.x;

        this._acc.y=event.acc.y;
    },
   
     update: function  (dt) {
        var  target=this.target,range=this._range;

        this._time+=5;
        target.x+=this._acc.x*dt(this.speed+this._time);
        target.x=cc.clamf(target.x,-range.x,range.x);

        target.y+=this._acc.y*dt*(this.speed+this._time);
        target.y=cc.clamf(target.y,-range.y,range.y);

        if(target.x<=-range.x || target.x>=range.x ||target.y<=-range.y ||target.y>=range.y)
        {
            this._time=0;
        }

     },
});
